
#include "particlefactory.h"

#include <math.h>

#include "waterparticle.h"

ParticleFactory::ParticleFactory(void)
{
	type = WATER;
}
ParticleFactory::ParticleFactory(int t)
{
	type = t;
}


void ParticleFactory::config(int pps, 
							 float *rad, float *pos, float *spr, 
							 float *vel, float life)
{
	pPerSec = pps;
	pPosRadius = new float[3];
		pPosRadius[0]=rad[0]; pPosRadius[1]=rad[1]; pPosRadius[2]=rad[2];
	pPosition = new float[3];
		pPosition[0]=pos[0]; pPosition[1]=pos[1]; pPosition[2]=pos[2]; 
	pSpread = new float[3];
		pSpread[0]=spr[0]; pSpread[1]=spr[1]; pSpread[2]=spr[2];
	pVelocity = new float[3];
		pVelocity[0]=vel[0]; pVelocity[1]=vel[1]; pVelocity[2]=vel[2];

	/*std::cout << "\tpPosRadius: " << pPosRadius[0] << " " << pPosRadius[1] << " " << pPosRadius[2] << "\n"
			  << "\tpPosition: " << pPosition[0] << " " << pPosition[1] << " " << pPosition[1] << "\n"
			  << "\tpSpread: " << pSpread[0] << " " << pSpread[1] << " " << pSpread[2] << "\n"
			  << "\tpVelocity: " << pVelocity[0] << " " << pVelocity[1] << " " << pVelocity[2] << std::endl;
	*/
	pLifespan = life;
}


Particle **ParticleFactory::update(float etime, int &num)
{
	if (type==WATER) 
		return (Particle **)getWaterParticles(etime, num);
	return NULL;
}

WaterParticle **ParticleFactory::getWaterParticles(float etime, int &num)
{
	num = (int)ceil(pPerSec*etime);
	//std::cout << "   Getting water particles: " << num << std::endl;
	WaterParticle **retList = new WaterParticle*[num];
	for(int i=0; i<num; i++)
	{
		float x,y,z;
		if(pPosRadius[0]==0.f) x = 0.f;
		else				   x = (float) (rand()%(int)(pPosRadius[0]*100));
		if(pPosRadius[1]==0.f) y = 0.f;
		else				   y = (float) (rand()%(int)(pPosRadius[1]*100));
		if(pPosRadius[2]==0.f) z = 0.f;
		else				   z = (float) (rand()%(int)(pPosRadius[2]*100));
		x/=100.0;   y/=100.0;   z/=100.0;
		x+=pPosition[0];    y+=pPosition[1];    z+=pPosition[2];
		//std::cout << x << " " << y << " " << z << std::endl;

		float dx, dy, dz;
		if(pSpread[0]==0.f) dx = 0.f;
		else				dx = (float)(rand()%(int)(pSpread[0]*100));
		if(pSpread[1]==0.f) dy = 0.f;
		else				dy = (float) (rand()%(int)(pSpread[1]*100));
		if(pSpread[2]==0.f) dz = 0.f;
		else				dz = (float) (rand()%(int)(pSpread[2]*100));
		dx/=100.0;   dy/=100.0;   dz/=100.0;
		//std::cout << "     spread: " << dx << "\t" << dy << "\t" << dz << std::endl;
		dx -= pSpread[0]/2.f;   dy -= pSpread[1]/2.f;   dz -= pSpread[2]/2.f;
		dx+=pVelocity[0];   dy+=pVelocity[1];   dz+=pVelocity[2];

		float life = pLifespan + (float)(((rand()%40 - 20)/100.0));
		//std::cout << "life: " << life << std::endl;

		retList[i] = new WaterParticle(life, x,y,z, dx,dy,dz);
		retList[i]->acc.set(1,-9.8f);
	}
	return retList;
}
